package com.leyou.item.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.constants.MQConstants.Tag;
import com.leyou.common.constants.MQConstants.Topic;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.pojo.Brand;
import com.leyou.item.pojo.Category;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.Spu;
import com.leyou.item.pojo.SpuDetail;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @date: 2021/3/31 0031 17:22
 * @description:
 */

@Service
@Transactional
public class GoodsService extends ServiceImpl<SkuMapper, Sku> {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    /**
     * 分页查询商品
     */
    public PageResult<SpuDTO> spuPageQuery(Integer page, Integer rows, String key, Boolean saleable) {
        //1. 创建分页查询条件
        //1.1 分页参数
        IPage<Spu> iPage = new Page(page, rows);

        //1.2 查询条件
        QueryWrapper<Spu> queryWrapper = Wrappers.query();

        //1.3 处理key
        if (StringUtils.isNotEmpty(key)) {
            // SELECT * FROM tb_spu WHERE `name` LIKE '%key%' OR sub_title LIKE '%key%'
            queryWrapper.and(
                    i -> i.like("name", key)
                            .or()
                            .like("sub_title", key)
            );
        }

        //1.4 处理saleable
        if (saleable != null) {
            queryWrapper.eq("saleable", saleable);
        }

        //2. 执行查询语句
        iPage = spuMapper.selectPage(iPage, queryWrapper);

        //3. 封装并返回结果
        //3.1 获取分页数据
        List<Spu> spuList = iPage.getRecords();

        //3.2 将spu集合转换为spuDto集合
        List<SpuDTO> spuDTOList = BeanHelper.copyWithCollection(spuList, SpuDTO.class);

        //3.3 封装categoryName和brandName
        getCategoryNameAndBrandName(spuDTOList);

        PageResult pageResult = new PageResult(iPage.getTotal(), iPage.getPages(), spuDTOList);
        return pageResult;
    }

    /**
     * 获取categoryName和brandName
     *
     * @param spuDTOList
     */
    private void getCategoryNameAndBrandName(List<SpuDTO> spuDTOList) {
        //获取categoryName
        //遍历spuDTOList
        spuDTOList.forEach(spuDTO -> {
            //封装brand
            Brand brand = brandService.findBrandById(spuDTO.getBrandId());
            spuDTO.setBrandName(brand.getName());

            //封装category
            List<Category> categoryList = categoryService.findCategoriesByCids(Arrays.asList(spuDTO.getCid1(), spuDTO.getCid2(), spuDTO.getCid3()));
            String categoryName = categoryList.stream().map(Category::getName).collect(Collectors.joining("/"));
            spuDTO.setCategoryName(categoryName);
        });
    }


    /**
     * 新增商品信息
     */
    public void saveGoods(SpuDTO spuDTO) {
        try {
            //1. 保存Spu表
            //拷贝数据
            Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);

            //默认下架
            spu.setSaleable(false);
            spuMapper.insert(spu);

            //2. 保存spu_detail表
            SpuDetail spuDetail = spuDTO.getSpuDetail();
            spuDetail.setSpuId(spu.getId());
            spuDetailMapper.insert(spuDetail);

            //3.保存sku表
            List<Sku> skus = spuDTO.getSkus();
            skus.forEach(sku -> {
                sku.setSpuId(spu.getId());
            });
            saveBatch(skus);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }


    /**
     * 修改商品上下架
     */
    public void updateSaleable(Long id, Boolean saleable) {
        try {
            Spu spu = new Spu();
            spu.setId(id);
            spu.setSaleable(saleable);

            //根据saleable获取主题标签
            String tagName = saleable ? Tag.ITEM_UP_TAG : Tag.ITEM_DOWN_TAG;
            String destination = Topic.ITEM_TOPIC_NAME + ":" + tagName;

            //发送消息给MQ
            /**
             * 参数一：目的地，只写topic也可以写topic：tag
             * 参数二：消息内容
             */
            rocketMQTemplate.convertAndSend(destination,id);

            //修改状态
            spuMapper.updateById(spu);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

    }


    /**
     * 根据spuId查询Sku集合
     */
    public List<Sku> findSkusBySpuId(Long id) {
        //封装查询条件
        QueryWrapper queryWrapper = Wrappers.query();
        queryWrapper.eq("spu_id", id);

        //查询数据
        List<Sku> skus = skuMapper.selectList(queryWrapper);

        if (CollectionUtils.isEmpty(skus)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return skus;
    }


    /**
     * 根据spuId查询SpuDetail
     */
    public SpuDetail findSpuDetailBySpuId(Long id) {
        SpuDetail spuDetail = spuDetailMapper.selectById(id);

        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return spuDetail;
    }


    /**
     * 根据spuId查询SpuDTO对象
     */
    public SpuDTO findSpuDTOBySpuId(Long id) {
        //1.查询Spu对象
        Spu spu = spuMapper.selectById(id);

        //2.拷贝数据
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);

        //3.查询SpuDetail并封装
        SpuDetail spuDetail = spuDetailMapper.selectById(id);
        spuDTO.setSpuDetail(spuDetail);

        //4.查询Spu下的Sku对象
        List<Sku> skus = findSkusBySpuId(id);
        spuDTO.setSkus(skus);
        return spuDTO;
    }

}
